# -*- coding: UTF-8 -*-
from collections import defaultdict
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
        # 存放朋友亲密度的索引值
        prefs = [[-1] * n for _ in range(n)]
        for i in range(len(preferences)):
            pref_array = preferences[i]
            for q, friend in enumerate(pref_array):
                prefs[i][friend] = q

        # 存放配对信息
        pair_dict = defaultdict(list)
        for i, pair in enumerate(pairs):
            pair_dict[pair[0]].append(pair[1])
            pair_dict[pair[1]].append(pair[0])

        ans_dict = defaultdict(int) # 即使他有多个配对都是不愉快，一个朋友只统计一次不愉快，
        ans = 0

        for x in range(n):
            if ans_dict[x] != 0:
                continue

            x_paired_friends = pair_dict[x]
            if len(x_paired_friends) > 0:
                for _, y in enumerate(x_paired_friends):
                    q_y = prefs[x][y]
                    if q_y > 0:
                        for i in range(q_y):
                            u = preferences[x][i]
                            q_u_x = prefs[u][x]

                            u_paired_friends = pair_dict[u]
                            if len(u_paired_friends) > 0:
                                for v in u_paired_friends:
                                    if v != x and v != y:
                                        q_u_v = prefs[u][v]
                                        if q_u_x < q_u_v:
                                            if ans_dict[x] == 0:
                                                ans_dict[x] += 1
                                                ans += 1
        return ans


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        (4, [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], [[1, 3], [0, 2]], 4),
        (4, [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], [[0, 1], [2, 3]], 2),
        (2, [[1], [0]], [[1, 0]], 0)
    ]

    for case_item in testcases:
        # 获取测试用的case和期待的执行结果
        input1 = case_item[0]
        input2 = case_item[1]
        input3 = case_item[2]
        expect = case_item[len(case_item) - 1]

        exec_result = solution.unhappyFriends(input1, input2, input3)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

